from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
from main_window_ui import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, db_manager, user_id, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.db_manager = db_manager
        self.user_id = user_id

        # 连接信号槽
        self.ui.minimizeButton.clicked.connect(self.showMinimized)
        self.ui.closeButton.clicked.connect(self.close)
        self.ui.saveCaloriesButton.clicked.connect(self.save_calories)
        self.ui.saveWeightButton.clicked.connect(self.save_weight)
        self.ui.deleteCaloriesButton.clicked.connect(self.delete_calories_record)
        self.ui.deleteWeightButton.clicked.connect(self.delete_weight_record)

        # 添加页面切换按钮连接
        self.ui.caloriesButton.clicked.connect(self.show_calories_page)
        self.ui.weightButton.clicked.connect(self.show_weight_page)

        # 设置窗口无边框和可拖动
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.dragging = False
        self.offset = None

        # 初始化UI
        self.init_ui()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.offset = event.pos()

    def mouseMoveEvent(self, event):
        if self.dragging and self.offset is not None:
            self.move(self.pos() + event.pos() - self.offset)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = False
            self.offset = None

    def init_ui(self):
        # 设置日期为今天
        today = QtCore.QDate.currentDate()
        self.ui.dateEdit_cal.setDate(today)
        self.ui.dateEdit_weight.setDate(today)

        # 初始化表格
        self.init_calories_table()
        self.init_weight_table()

        # 加载历史数据
        self.load_calories_history()
        self.load_weight_history()

        # 设置堆叠窗口默认显示卡路里页面
        self.ui.stackedWidget.setCurrentIndex(0)

        # 设置初始按钮状态
        self.ui.caloriesButton.setChecked(True)
        self.ui.weightButton.setChecked(False)

    def init_calories_table(self):
        """初始化卡路里表格"""
        # 设置为9列以包含ID列
        self.ui.caloriesTable.setColumnCount(9)
        self.ui.caloriesTable.setHorizontalHeaderLabels([
            "ID", "日期", "早餐", "早餐卡路里", "午餐", "午餐卡路里", "晚餐", "晚餐卡路里", "总计"
        ])
        # 隐藏ID列
        self.ui.caloriesTable.setColumnHidden(0, True)
        self.ui.caloriesTable.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)

    def init_weight_table(self):
        """初始化体重表格"""
        self.ui.weightTable.setColumnCount(3)
        self.ui.weightTable.setHorizontalHeaderLabels(["ID", "日期", "体重(kg)"])
        # 隐藏ID列
        self.ui.weightTable.setColumnHidden(0, True)
        self.ui.weightTable.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)

    def save_calories(self):
        """保存卡路里记录"""
        try:
            date = self.ui.dateEdit_cal.date().toPyDate()
            breakfast = self.ui.breakfastEdit.text().strip()
            b_cal = self.ui.breakfastCalories.value()
            lunch = self.ui.lunchEdit.text().strip()
            l_cal = self.ui.lunchCalories.value()
            dinner = self.ui.dinnerEdit.text().strip()
            d_cal = self.ui.dinnerCalories.value()
            total = b_cal + l_cal + d_cal

            # 验证至少输入了一餐
            if not breakfast and not lunch and not dinner:
                QtWidgets.QMessageBox.warning(self, "错误", "请至少输入一顿餐食")
                return

            # 保存到数据库
            if self.db_manager.add_calories_record(self.user_id, date, breakfast, b_cal, lunch, l_cal, dinner, d_cal,
                                                   total):
                QtWidgets.QMessageBox.information(self, "成功", "卡路里记录已保存")
                self.clear_calories_form()
                self.load_calories_history()
            else:
                QtWidgets.QMessageBox.warning(self, "错误", "保存失败")
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "错误", f"保存卡路里记录失败: {str(e)}")

    def clear_calories_form(self):
        """清空卡路里输入表单"""
        self.ui.breakfastEdit.clear()
        self.ui.breakfastCalories.setValue(0)
        self.ui.lunchEdit.clear()
        self.ui.lunchCalories.setValue(0)
        self.ui.dinnerEdit.clear()
        self.ui.dinnerCalories.setValue(0)

    def load_calories_history(self):
        """加载卡路里历史记录"""
        try:
            history = self.db_manager.get_calories_history(self.user_id)
            self.ui.caloriesTable.setRowCount(len(history))

            for row, record in enumerate(history):
                id, date, breakfast, b_cal, lunch, l_cal, dinner, d_cal, total = record
                date_str = date.strftime("%Y-%m-%d")

                # 创建表格项并添加到表格
                self.ui.caloriesTable.setItem(row, 0, QtWidgets.QTableWidgetItem(str(id)))
                self.ui.caloriesTable.setItem(row, 1, QtWidgets.QTableWidgetItem(date_str))
                self.ui.caloriesTable.setItem(row, 2, QtWidgets.QTableWidgetItem(breakfast))
                self.ui.caloriesTable.setItem(row, 3, QtWidgets.QTableWidgetItem(str(b_cal)))
                self.ui.caloriesTable.setItem(row, 4, QtWidgets.QTableWidgetItem(lunch))
                self.ui.caloriesTable.setItem(row, 5, QtWidgets.QTableWidgetItem(str(l_cal)))
                self.ui.caloriesTable.setItem(row, 6, QtWidgets.QTableWidgetItem(dinner))
                self.ui.caloriesTable.setItem(row, 7, QtWidgets.QTableWidgetItem(str(d_cal)))
                self.ui.caloriesTable.setItem(row, 8, QtWidgets.QTableWidgetItem(str(total)))
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "错误", f"加载卡路里历史失败: {str(e)}")

    def save_weight(self):
        """保存体重记录"""
        try:
            date = self.ui.dateEdit_weight.date().toPyDate()
            weight = self.ui.weightEdit.value()

            # 验证输入
            if weight <= 0:
                QtWidgets.QMessageBox.warning(self, "错误", "请输入有效的体重")
                return

            # 保存到数据库
            if self.db_manager.add_weight_record(self.user_id, date, weight):
                QtWidgets.QMessageBox.information(self, "成功", "体重记录已保存")
                self.ui.weightEdit.setValue(0)
                self.load_weight_history()
            else:
                QtWidgets.QMessageBox.warning(self, "错误", "保存失败")
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "错误", f"保存体重记录失败: {str(e)}")

    def load_weight_history(self):
        """加载体重历史记录"""
        try:
            history = self.db_manager.get_weight_history(self.user_id)
            self.ui.weightTable.setRowCount(len(history))

            for row, record in enumerate(history):
                id, date, weight = record
                date_str = date.strftime("%Y-%m-%d")

                # 设置3列（ID列隐藏）
                self.ui.weightTable.setItem(row, 0, QtWidgets.QTableWidgetItem(str(id)))
                self.ui.weightTable.setItem(row, 1, QtWidgets.QTableWidgetItem(date_str))
                self.ui.weightTable.setItem(row, 2, QtWidgets.QTableWidgetItem(f"{weight} kg"))
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "错误", f"加载体重历史失败: {str(e)}")

    def delete_calories_record(self):
        """删除选中的卡路里记录"""
        selected_row = self.ui.caloriesTable.currentRow()
        if selected_row == -1:
            QtWidgets.QMessageBox.warning(self, "警告", "请选择要删除的记录")
            return

        record_id = int(self.ui.caloriesTable.item(selected_row, 0).text())

        reply = QtWidgets.QMessageBox.question(
            self, "确认删除",
            "确定要删除这条记录吗?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
            QtWidgets.QMessageBox.No
        )

        if reply == QtWidgets.QMessageBox.Yes:
            try:
                # 从数据库删除
                self.db_manager.cursor.execute("DELETE FROM calories WHERE id = %s", (record_id,))
                self.db_manager.connection.commit()

                # 从表格删除
                self.ui.caloriesTable.removeRow(selected_row)
                QtWidgets.QMessageBox.information(self, "成功", "记录已删除")
            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "错误", f"删除记录失败: {str(e)}")

    def delete_weight_record(self):
        """删除选中的体重记录"""
        selected_row = self.ui.weightTable.currentRow()
        if selected_row == -1:
            QtWidgets.QMessageBox.warning(self, "警告", "请选择要删除的记录")
            return

        record_id = int(self.ui.weightTable.item(selected_row, 0).text())

        reply = QtWidgets.QMessageBox.question(
            self, "确认删除",
            "确定要删除这条记录吗?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
            QtWidgets.QMessageBox.No
        )

        if reply == QtWidgets.QMessageBox.Yes:
            try:
                # 从数据库删除
                self.db_manager.cursor.execute("DELETE FROM weights WHERE id = %s", (record_id,))
                self.db_manager.connection.commit()

                # 从表格删除
                self.ui.weightTable.removeRow(selected_row)
                QtWidgets.QMessageBox.information(self, "成功", "记录已删除")
            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "错误", f"删除记录失败: {str(e)}")

    def show_calories_page(self):
        """显示卡路里管理页面"""
        self.ui.stackedWidget.setCurrentIndex(0)
        self.ui.caloriesButton.setChecked(True)
        self.ui.weightButton.setChecked(False)

    def show_weight_page(self):
        """显示体重管理页面"""
        self.ui.stackedWidget.setCurrentIndex(1)
        self.ui.caloriesButton.setChecked(False)
        self.ui.weightButton.setChecked(True)